<template>
	<el-dialog v-model="visible" :title="(isView ? '查看': !dataForm.id ? '新建' : '编辑')+(inventory_type==1?'入库单':'出库单')" :close-on-click-modal="false" :width="dwidth" center destroy-on-close>
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="80px" v-loading="pageloading">
            <div class="flex" v-if="inventory_type==1">
                <div>
                    <el-form-item  label="入库时间" prop="in_time">
                        <el-date-picker
                            v-model="dataForm.in_time"
                            type="datetime"
                            placeholder="请选择入库时间"

                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                             style="width: 230px;"
                            :disabled="isView"
                        />
                    </el-form-item>
                </div>
                <div class="ml10">
                    <el-form-item  label="入库类型" prop="in_type">
                        <el-select v-model="dataForm.in_type" :filterable="canfilterable" clearable placeholder="请输入" :disabled="isView" style="width: 230px;">
                            <el-option label="产品采购入库" :value="1" />
                            <el-option label="材料采购入库" :value="2" />
                            <el-option label="退货入库" :value="3" />
                        </el-select>
                    </el-form-item>
                </div>
            </div>
			<div class="flex" v-if="inventory_type==1">
                <div>
                    <div class="flex">
                        <el-form-item  label="供应商" prop="supplier_name">
                            <el-select v-model="dataForm.supplier_name" :filterable="canfilterable" clearable allow-create placeholder="请输入选择供应商" :disabled="isView" style="width: 230px;">
                                <el-option
                                v-for="item in supplierList"
                                :key="item.id"
                                :label="item.label"
                                :value="item.label"
                                />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
                <div class="ml10">
                    <el-form-item  label="批次号" prop="batch_no">
                        <el-input v-model="dataForm.batch_no" placeholder="请输入批次号" maxlength="255" style="width: 230px;" :disabled="isView"></el-input>
                    </el-form-item>
                </div>
            </div>
			<div class="flex" v-if="chooseUserList.length">
                <div>
                    <div class="flex">
                        <el-form-item  label="分摊人">
                            <div class="w100">
                                <div class="w100" v-for="user,i in chooseUserList" :key="i">
                                    <div class="flex flexL" style="width: 240px;">
                                        <div style="width: 40%;">{{ user.label }}</div>
                                        <div style="width: 60%;">{{ user.rate }}</div>
                                    </div>
                                </div>
                            </div>
                        </el-form-item>
                    </div>
                    
                </div>
            </div>
            <div class="flex" v-if="inventory_type==2">
                <div>
                    <el-form-item  label="出库时间" prop="out_time">
                        <el-date-picker
                            v-model="dataForm.out_time"
                            type="datetime"
                            placeholder="请选择出库时间"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            style="width: 230px;"
                            :disabled="isView"
                        />
                    </el-form-item>
                </div>
                <div class="ml10">
                    <el-form-item  label="出库类型" prop="out_type">
                        <el-select v-model="dataForm.out_type" :filterable="canfilterable" clearable placeholder="请输入" :disabled="isView" style="width: 230px;">
                            <el-option label="生产出库" :value="1" />
                            <el-option label="销售出库" :value="2" />
                        </el-select>
                    </el-form-item>
                </div>
                <!-- <div class="ml10">
                    <el-button type="primary" size="small">哑光6色</el-button>
                    <el-button type="primary" size="small">哑光8色</el-button>
                </div> -->
            </div>
            <div class="flex" v-if="inventory_type==1">
                <div class="flex1">
                    <el-form-item  label="入库备注" prop="remark">
                        <el-input v-model="dataForm.remark" placeholder="请输入备注" maxlength="5000" style="width: 100%;" :disabled="isView"></el-input>
                    </el-form-item>
                </div>
            </div>
            <div class="flex" v-if="inventory_type==2">
                <div>
                    <div class="flex">
                        <el-form-item  label="客户" prop="customer_name">
                            <el-select v-model="dataForm.customer_name" :disabled="isView||!!dataForm.department_id" :filterable="canfilterable" clearable allow-create placeholder="请输入选择客户" style="width: 230px;">
                                <el-option
                                v-for="item in customerList"
                                :key="item.id"
                                :label="item.label"
                                :value="item.label"
                                />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
                <div class="ml10">
                    <div class="flex">
                        <el-form-item  label="部门" prop="department_id">
                            <el-select v-model="dataForm.department_id" :disabled="isView||!!dataForm.customer_name" :filterable="canfilterable" clearable allow-create placeholder="请输入选择部门" style="width: 230px;">
                                <el-option
                                v-for="item in departmentList"
                                :key="item.id"
                                :label="item.label"
                                :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </div>
                </div>
            </div>
            <div class="flex" v-if="inventory_type==2">
                <div class="ml10 flex1">
                    <el-form-item  label="出库备注" prop="remark">
                        <el-input v-model="dataForm.remark" placeholder="请输入备注" maxlength="5000" style="width: 100%;" :disabled="isView"></el-input>
                    </el-form-item>
                </div>
            </div>
			<div class="table-content">
				<table class="table tablec">
					<tr class="tr">
						<td class="td th">*产品</td>
						<td class="td th">属性</td>
						<td class="td th" v-if="!isView">当前库存</td>
						<td class="td th" v-if="isFt">成本价</td>
						<td class="td th">
                            <span v-if="inventory_type==1">*入库数量</span>
                            <span v-if="inventory_type==2">*出库数量</span>
                        </td>
						<td class="td th" v-if="isFt">
                            <span>应分摊金额</span>
                        </td>
						<!-- <td class="td th">*进货单价</td>
						<td class="td th">金额</td> -->
                        <template v-if="isFt">
                            <td class="td th" v-for="user,i in chooseUserList" :key="i">{{ user.label }}</td>
                        </template>
						<td class="td th" v-if="!isView">操作</td>
					</tr>
					<tr class="tr" v-for="(item,index) in options" :key="item.id">
						<td class="td">
							<el-select v-model="item.productName" placeholder="请输入选择产品" :filterable="canfilterable" style="width: 100%;" :disabled="isView" @change="selectChange(index, $event)">
								<el-option v-for="i in productList" :disabled="disOption(i.label, options[0])" :key="i.value" :label="i.label" :value="i.label" />
							</el-select>
						</td>
						<td class="td">
							<el-select v-model="item.productId" placeholder="请输入选择属性" :filterable="canfilterable" style="width: 100%;" no-data-text="请先选择产品" :disabled="isView||(has_bt_pro_name.includes(item.productName)&&!btlist_loadok)" @change="selectChange2(index, $event)">
								<el-option v-for="i in item.attrList" :key="i.value" :label="i.label" :value="i.value" />
							</el-select>
						</td>
						<td class="td" v-if="!isView">
							<div style="width: 220px;">
                                <div class="w100 flex flexL" v-if="inventory_type==2&&item.batchList?.length">
                                    <div class="w70">
                                        <el-select v-model="item.batch_id" placeholder="请输入批次号" :filterable="canfilterable" style="width: 100%;" no-data-text="请先选择产品" :disabled="isView" @change="selectChange3(index, $event)">
                                            <el-option v-for="i in item.batchList" :key="i.id" :label="i.batch_no" :value="i.batch_id" />
                                        </el-select>
                                    </div>
                                    <div class="w30">
                                        {{ item.inventory }}
                                    </div>
                                </div>
                                <div v-else>{{ item.inventory }}</div>
                            </div>
						</td>
						<td class="td" v-if="isFt">
							{{ item.make_price }}
						</td>
						<td class="td">
                            <span v-if="inventory_type==2&&item.batchNo&&isView" class="pr10">批次号：{{ item.batchNo }}</span>
							<el-input v-model="item.quantity" placeholder="请输入数量" @mousewheel.native.prevent :disabled="isView" @input="notNoNumber(item,'quantity',$event, setAmount(index))" type="number" style="width: 120px;" />
						</td>
						<td class="td" v-if="isFt">
							{{ setFtTotal(item) }}
						</td>
						<!-- <td class="td">
							<el-input v-model="item.price" placeholder="请输入单价" :disabled="isView" @input="notNoNumber(item,'price',$event, setAmount(index))" type="number" style="width: 120px;" />
						</td>
						<td class="td">
							<el-input v-model="item.total_price" placeholder="请输入金额" :disabled="isView" @input="notNoNumber(item,'total_price',$event)" type="number" style="width: 120px" />
						</td> -->
                        <template v-if="isFt">
                            <td class="td" v-for="user,i in chooseUserList" :key="i">
                                <div style="min-width: 120px;">
                                    <div style="width: 100%;" class="textL">数量：{{ setFtNum(item, user, i) }}</div>
                                    <div style="width: 100%;" class="textL">成本：{{ setFtPrice(item, user, i) }}</div>
                                </div>
                            </td>
                        </template>
						<td class="td" v-if="!isView">
							<!-- <el-icon @click="add()" v-if="index == 0" class="pointer" :size="24"><CirclePlusFilled /></el-icon> -->
							<el-icon @click="del(index)" class="pointer" :size="24"><RemoveFilled /></el-icon>
						</td>
					</tr>
					<tr class="tr" v-if="isFt">
						<td class="td" :colspan="!isView ? 4 : 3">
							<div class="w100 textR">汇总</div>
						</td>
						<td class="td">
							{{ contentTotal }}
						</td>
						<td class="td">
							{{ contentPriceTotal }}
						</td>
                        <td class="td" v-for="user,i in chooseUserList" :key="i">
                            <div style="min-width: 120px;">
                                <div style="width: 100%;" class="textL">数量：{{ setFtNumTotal(user, i) }}</div>
                                <div style="width: 100%;" class="textL">成本：{{ setFtPriceTotal(user, i) }}</div>
                            </div>
                        </td>
						<td class="td" v-if="!isView">
							
						</td>
					</tr>
				</table>
			</div>
            <div class="flex mt10">
                <div v-if="!isView">快捷操作：</div>
                <div class="flex1">
                    <div v-if="!isView&&btlist_loadok">
                        <el-button color="#333" size="small" @click="outInvent(1,6)">哑光6</el-button>
                        <el-button color="#333" size="small" @click="outInvent(1,8)">哑光8</el-button>
                        <el-button color="#333" size="small" @click="outInvent(1,12)">哑光12</el-button>
                        <el-button color="#48AAC5" size="small" @click="outInvent(2,6)">荧光6</el-button>
                        <el-button color="#48AAC5" size="small" @click="outInvent(2,8)">荧光8</el-button>
                        <el-button color="#48AAC5" size="small" @click="outInvent(2,12)">荧光12</el-button>
                        <el-button color="#F494AB" size="small" @click="outInvent(3,6)">珠光6</el-button>
                        <el-button color="#F494AB" size="small" @click="outInvent(3,8)">珠光8</el-button>
                        <el-button color="#F494AB" size="small" @click="outInvent(3,12)">珠光12</el-button>
                    </div>
                </div>
                <div style="padding-right: 15px;">
                    <el-icon v-if="!isView" @click="add()" class="pointer" :size="24"><CirclePlusFilled /></el-icon>
                </div>
            </div>
            <div class="textR pt5 pb5 bold font16" :style="{'padding-right': isView ? '115px' : '170px'}" v-if="inventory_type==1&&!isFt">入库总数：{{ contentTotal }}</div>
            <div class="textR pt5 pb5 bold font16" :style="{'padding-right': isView ? '115px' : '170px'}" v-if="inventory_type==2&&!isFt">出库总数：{{ contentTotal }}</div>
			<!-- <div class="flex flexL mt20">
				<div class="mr10">合计：</div>
				<div>
					<el-input v-model="totalAmount" disabled type="number" style="width: 120px;" />
				</div>
			</div> -->
		</el-form>
		<template #footer>
			<el-button @click="visible = false">{{ isView ? '关闭': '取消' }}</el-button>
			<el-button type="warning" @click="submitHandle(1)" :loading="btnloading" v-if="!isView">保存草稿</el-button>
			<el-button type="primary" @click="submitHandle(2)" :loading="btnloading" v-if="!isView && ((inventory_type==1&&hasRule('admin/inventory/in/confirm'))||(inventory_type==2&&hasRule('admin/inventory/out/confirm')))">{{ inventory_type==1 ? '确定入库' : '确定出库' }}</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { Plus, Minus, CirclePlusFilled, RemoveFilled } from '@element-plus/icons-vue'
import { reactive, ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus/es'
import { getSupplierList, getCustomerList, getProductSkuList, addInventory, getInventory, getInventoryItem, getBatchList } from '@/api/api'
import { Storage } from '@/utils/storage'
import { BASE_URL } from '@/config'
import { decrypt, encrypt, copy, timeResetDate, notNoNumber, hasRule } from '@/utils/tool'
import { departmentwithuser } from '@/api/org'

const isDevelopment = import.meta.env.MODE == 'development';
const emit = defineEmits(['refreshDataList'])
const typeList1 = ref([])
const supplierList = ref([])
const customerList = ref([])
const departmentList = ref([])
const isView = ref(false)
const productAllList = ref([])
const productList = ref([])
const visible = ref(false)
const isFt = ref(false) // 是否采购单）分摊
const btnloading = ref(false)
const pageloading = ref(false)
const canfilterable = ref(true)
const dataFormRef = ref()
const bindUrl = ref('')
const purchase_no = ref('')
const share_contents = ref('')
const dwidth = ref('980px');
const inventory_type = ref(1);
const chooseUser = ref([])
const chooseUserList = ref([])
const has_bt_pro_name = ref(['心型染发夹']);
const btlist_loadok = ref(false);
const dataForm = reactive({
	id: 0,
	remark: '',
	in_time: '',
	batch_no: '',
	out_time: '',
	type: '',
	in_type: '',
	out_type: '',
	status: '',
	supplier_name: '',
	customer_name: '',
	department_id: '',
	department_name: '',
	contents: '',
	order_sn: '',
})
const dataRules = ref({
	// in_time: [{ required: true, message: '必填项不能为空', trigger: ['blur','change'] }],
	// in_type: [{ required: true, message: '必填项不能为空', trigger: ['blur','change'] }],
	// supplier_name: [{ required: true, message: '必填项不能为空', trigger: ['blur','change'] }],
})
const totalAmount = ref('')
const options: any = ref([
    {
        productId: '',
        productName: '',
        inventory: 0,
        make_price: 0,
        quantity: '',
        attrList: [],
        batch_id: '',
        batchNo: '',
        batchList: [],
    }
])
const contentTotal = computed(() => {
    let total = options.value.reduce((to, it) => {
        return to + Number(it.quantity)
    }, 0);
    return Number((total).toFixed(2));
})
const contentPriceTotal = computed(() => {
    let total = options.value.reduce((to, it) => {
        return to + Number(it.quantity*it.make_price)
    }, 0);
    return Number((total).toFixed(4));
})
// 计算单品分摊总额
const setFtTotal = (item) => {
    if(item?.quantity){
        return Number((item.quantity*item.make_price).toFixed(4));
    }else{
        return 0;
    }
}
// 计算单品各自数量
const setFtNum = (item, user, idx) => {
    if(item?.quantity&&user?.rate){
        // 最后一列让前面的射出来计算
        if(idx == chooseUserList.value.length - 1) {
            const frontList = chooseUserList.value.slice(0, chooseUserList.value.length-1);
            const frontTotal = frontList.reduce((total, isss) => {
                return total + Number((item.quantity*isss.rate).toFixed(0))
            }, 0)
            return Number((item.quantity-frontTotal).toFixed(0));
        }else{
            return Number((item.quantity*user.rate).toFixed(0));
        }
    }else{
        return 0;
    }
}
// 计算单品各自成本
const setFtPrice = (item, user, idx) => {
    if(item?.quantity&&user?.rate){
        // 最后一列让前面的射出来计算
        if(idx == chooseUserList.value.length - 1) {
            const frontList = chooseUserList.value.slice(0, chooseUserList.value.length-1);
            const frontTotal = frontList.reduce((total, isss) => {
                return total + Number((item.quantity*isss.rate).toFixed(0))
            }, 0)
            return Number((item.quantity-frontTotal).toFixed(0)*item.make_price).toFixed(4);
        }else{
            return Number((item.quantity*user.rate).toFixed(0)*item.make_price).toFixed(4);
        }
    }else{
        return 0;
    }
}
// 计算总各自数量
const setFtNumTotal = (user, idx) => {
    if(user?.rate){
        if(idx == chooseUserList.value.length - 1){
            let frontTotal = 0;
            const frontList = chooseUserList.value.slice(0, chooseUserList.value.length-1);
            frontList.forEach(iiss => {
                const totalitem = options.value.reduce((total,item) => {
                    return total + Number((item.quantity*iiss.rate).toFixed(0));
                }, 0)
                frontTotal += totalitem;
            })
            return Math.floor(contentTotal.value - frontTotal);
        }else{
            const total = options.value.reduce((total,item) => {
                return total + Number((item.quantity*user.rate).toFixed(0));
            }, 0)
            return Number(total);
        }
    }else{
        return 0;
    }
}
// 计算总各自成本
const setFtPriceTotal = (user, idx) => {
    if(user?.rate){
        if(idx == chooseUserList.value.length - 1){
            let frontTotal = 0;
            const frontList = chooseUserList.value.slice(0, chooseUserList.value.length-1);
            frontList.forEach(iiss => {
                const totalitem = options.value.reduce((total,item) => {
                    return total + ((item.quantity*iiss.rate).toFixed(0)*item.make_price);
                }, 0)
                frontTotal += totalitem;
            })
            return Number(contentPriceTotal.value - frontTotal).toFixed(4);
        }else{
            const total = options.value.reduce((total,item) => {
                return total + ((item.quantity*user.rate).toFixed(0)*item.make_price);
            }, 0)
            return Number(total).toFixed(4);
        }
    }else{
        return 0;
    }
}
const disOption = (productName, fitem) => {
    if(fitem?.productName && productName != fitem.productName && inventory_type==1){
        return true;
    }else{
        return false;
    }
}
const add = () => {
	options.value.push(
        {
            productId: '',
            productName: '',
            inventory: 0,
            make_price: 0,
            quantity: '',
            attrList: [],
            batch_id: '',
            batchNo: '',
            batchList: [],
        }
    )
}
const del = (i) => {
	options.value.splice(i,1)
}
const setAmount = (i) => {
	// if (options.value[i].quantity || options.value[i].price) {
	// 	options.value[i].total_price = (options.value[i].quantity * options.value[i].price).toFixed(2)
	// }
}
const selectChange = (i, val) => {
    // console.log(i, val);
	if (val) {
		const list = productAllList.value.filter(i => i.name == val);
        list.sort((a,b)=>a.sort-b.sort);
        // console.log('list', list);
		options.value[i].attrList = list.map(item => {
            let label = item.attr_name_fill+'-'+item.attr_name;
            if(!item.attr_name_fill){
                label = item.attr_name;
            }
            return {
                ...item,
                label: label,
                value: item.id,
            }
        })
		options.value[i].productId = ''
		options.value[i].batch_id = ''
		options.value[i].batchNo = ''
		options.value[i].inventory = ''
	} else {
		options.value[i].productId = ''
		options.value[i].batch_id = ''
		options.value[i].batchNo = ''
		options.value[i].inventory = ''
	}
    // console.log(val, options.value[i]);
}
const selectChange2 = (i, val) => {
    // console.log(i, val);
	if (val) {
		const item = productAllList.value.find(i => i.id == val)
		options.value[i].make_price = item.make_price;
		options.value[i].product_type = item.type_name_fill+'-'+item.type_name;
		options.value[i].product_attr = item.attr_name_fill+'-'+item.attr_name;
        if(item.batch_list_all?.length&&inventory_type.value==2){
            options.value[i].inventory = '';
            const batch_list_all = item.batch_list_all.filter(i => i.quantity > i.isused);
            let all_log = 0;
            options.value[i].batchList = batch_list_all.map(itee => {
                all_log += (itee.quantity - itee.isused);
                return {
                    batch_id: itee.id,
                    batch_no: itee.batch_no,
                    quantity: itee.quantity,
                    isused: itee.isused,
                }
            });
            console.log(all_log);
        }else{
            options.value[i].inventory = item.inventory;
            options.value[i].batchList = [];
        }
        // 废弃，采用接口返回批次列表，因为库存要实时更新的
        // console.log('item', item);
        // getInventoryItem({per_page:9999,page:1,product_id:val,type: 1}).then((result) => {
        //     const batchList = result.data.data?.filter(i => !!i.share_contents);
        //     if(batchList.length){
        //         options.value[i].inventory = '';
        //         options.value[i].batchList = batchList.map(itee => {
        //             return {
        //                 batch_no: itee.batch_no,
        //                 quantity: itee.quantity,
        //                 isused: itee.isused,
        //             }
        //         });
        //     }else{
        //         options.value[i].inventory = item.inventory;
        //         options.value[i].batchList = [];
        //     }
        // }).catch((err) => {
        //     options.value[i].inventory = item.inventory;
        // });
	}
}
const selectChange3 = (i, val) => {
    const item = options.value[i].batchList.find(i => i.batch_id == val);
    options.value[i].batchNo = item.batch_no;
    options.value[i].inventory = Math.floor(item.quantity - item.isused);
    // console.log(item);
}
watch(() => options.value, (val) => {
	let total: any = 0
	total = options.value.reduce((price, item) => {
		return price + Number(item.total_price||0)
	}, 0)
	totalAmount.value = total.toFixed(2)
}, {
	deep: true
})
const getList = (id) => {
	return new Promise((resolve) => {
        departmentwithuser({}).then((result) => {
            console.log(result.data);
            departmentList.value = result.data.map((item) => {
                return {
                    ...item,
                    label: item.department_name,
                    value: item.id,
                }
            })
        }).catch((err) => {
            
        });
        getSupplierList({page:1,per_page:9999}).then((result) => {
            // console.log(result.data.data);
            supplierList.value = result.data.data.map((item) => {
                return {
                    ...item,
                    label: item.name,
                    value: item.id,
                }
            })
        }).catch((err) => {
            
        });
        getCustomerList({page:1,per_page:9999}).then((result) => {
            // console.log(result.data.data);
            customerList.value = result.data.data.map((item) => {
                return {
                    ...item,
                    label: item.name,
                    value: item.id,
                }
            })
        }).catch((err) => {
            
        });
        if(isView.value===true){
            setTimeout(()=>{
                resolve(true);
            }, 500)
        }else{
            getProductSkuList({page:1,per_page:9999}).then((result) => {
                // console.log(result.data.data);
                // 记录全部产品
                productAllList.value = result.data.data.reverse();
                // 去掉重复产品
                const onleList = [];
                productAllList.value.forEach(item => {
                    item.batch_list_all = [];
                    if (!onleList.some(i => i.label == item.name)) {
                        onleList.push({
                            label: item.name,
                            value: item.id,
                        })
                    }
                });
                productList.value = onleList;
                getBatchList().then((result) => {
                    // console.log(result.data);
                    // 根据产品ID分组
                    const search_no = localStorage.getItem('search_no') || '495360';
                    localStorage.setItem('search_no', search_no);
                    let search_no_num = 0;
                    const pList = [];
                    result.data.forEach(item => {
                        if(item.batch_no.indexOf(search_no) != -1){
                            search_no_num += (item.quantity - item.isused);
                        }
                        const pitem = pList.find(i => i.product_id == item.product_id)
                        if (pitem) {
                            pitem.list.push(item);
                        }else{
                            pList.push({
                                product_id: item.product_id,
                                list: [item],
                            })
                        }
                    });
                    productAllList.value.forEach(item => {
                        const pitem = pList.find(i => i.product_id == item.id);
                        if(pitem){
                            item.batch_list_all = pitem.list;
                        }
                    });
                    if(id){
                        updateInve();
                    }
                    btlist_loadok.value = true;
                    console.log(search_no, search_no_num);
                    // console.log('pList', pList);
                }).catch((err) => {
                    
                });
                // console.log('productList.value', productList.value);
                resolve(true);
            }).catch((err) => {
                
            });
        }
    })
}
const init = async (id: any,type:any, v?: any, share_contents?: any) => {
    btlist_loadok.value = false;
    const userinfo = Storage.getItem('userinfo');
    if(userinfo.strator_mobile=='13778948627' && window.innerWidth < 1920){
        canfilterable.value = false;
    }else{
        canfilterable.value = true;
    }
    if(share_contents){
        isFt.value = true;
        dwidth.value = '1430px';
    }else{
        isFt.value = false;
        dwidth.value = '980px';
    }
    chooseUser.value = [];
    chooseUserList.value = [];
    inventory_type.value = type;
	dataForm.id = ''
    dataForm.remark = ''
    dataForm.in_time = timeResetDate();
    dataForm.batch_no = ''
    dataForm.out_time = timeResetDate();
    dataForm.type = ''
    dataForm.in_type = ''
    dataForm.out_type = ''
    dataForm.status = ''
    dataForm.supplier_name = ''
    dataForm.customer_name = ''
    dataForm.department_id = ''
    dataForm.department_name = ''
    dataForm.contents = ''
    dataForm.order_sn = ''
    options.value = [
        {
            productId: '',
            batch_id: '',
            batchNo: '',
            productName: '',
            inventory: 0,
            make_price: 0,
            quantity: '',
            attrList: [],
            batchList: [],
        }
    ]
	visible.value = true
	btnloading.value = false
	isView.value = v
	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}
	// id 存在则为修改
	if (id) {
        pageloading.value = true
        btnloading.value = true
        await getList(id);
        pageloading.value = false;
        btnloading.value = false;
        dataForm.id = id;
        getDetail(id)
	}else{
        getList();
    }
}
// 获取信息
const getDetail = (id: number) => {
	getInventory(id).then((res: any) => {
        // console.log('productAllList.value', productAllList.value);
        if (res.data.contents) {
            res.data.contents = JSON.parse(res.data.contents);
            // console.log(res.data.contents);
            if(isView.value===true){
                // 去掉重复产品
                const onleList = [];
                res.data.contents.forEach(item => {
                    if (!onleList.some(i => i.label == item.productName)) {
                        onleList.push({
                            label: item.productName,
                            value: item.productId,
                        })
                    }
                });
                productList.value = onleList;
            }
            options.value = res.data.contents;
            updateInve();
            // console.log(options.value);
        }
        if (res.data.share_contents) {
            share_contents.value = res.data.share_contents;
            res.data.share_contents = JSON.parse(res.data.share_contents);
            chooseUserList.value = res.data.share_contents;
            chooseUser.value = res.data.share_contents.map(i => i.id);
            // console.log(chooseUserList.value);
        }else{
            share_contents.value = '';
        }
        if(res.data.order_sn){
            purchase_no.value = res.data.order_sn;
        }else{
            purchase_no.value = '';
        }
        delete res.data.created_at;
        delete res.data.updated_at;
        delete res.data.deleted_at;
		Object.assign(dataForm, res.data);
	})
}
// 更新库存信息
const updateInve = () => {
    options.value.forEach(item => {
        if (item.productName) {
            if(isView.value===true){
                item.attrList = [
                    {
                        label: item.product_attr,
                        value: item.productId,
                    }
                ]
            }else{
                const list = productAllList.value.filter(i => i.name == item.productName)
                item.attrList = list.map(item => {
                    return {
                        ...item,
                        label: item.attr_name_fill+'-'+item.attr_name,
                        value: item.id,
                    }
                })
            }
        }
        if (item.batch_id) {
            if(isView.value===true){

            }else{
                const listItem = productAllList.value.find(i => i.id == item.productId);
                const batchItem = listItem.batch_list_all.find(i => i.id == item.batch_id);
                if(batchItem){
                    item.inventory = Math.floor(batchItem.quantity - batchItem.isused);;
                    item.make_price = listItem.make_price;
                }else{
                    item.inventory = listItem.inventory;
                    item.make_price = listItem.make_price;
                }
            }
        } else if(item.productId){
            if(isView.value===true){

            }else{
                const listItem = productAllList.value.find(i => i.id == item.productId)
                item.inventory = listItem.inventory;
                item.make_price = listItem.make_price;
            }
        }
    })
}
// 表单提交
const submitHandle = (status) => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
		if (options.value.some(i => !i.productName)) {
			ElMessage.warning('请选择产品')
			return
		}
		if (inventory_type.value == 1 && status == 2 && (!dataForm.in_time || !dataForm.in_type || !dataForm.supplier_name || options.value.some(i => !i.quantity || !i.productId || !i.productName))) {
			ElMessage.warning('请填写入库数据')
			return
		}
		if (inventory_type.value == 2 && status == 2 && (!dataForm.out_time || !dataForm.out_type || (!dataForm.customer_name&&!dataForm.department_id) || options.value.some(i => !i.quantity || !i.productId || !i.productName))) {
			ElMessage.warning('请填写出库数据')
			return
		}
        const emptyPro = options.value.find(i => +i.quantity > +i.inventory);
		if (emptyPro && status == 2 && inventory_type.value == 2) {
            console.log(emptyPro);
            const emptyDetail = emptyPro.attrList.find(i => i.id == emptyPro.productId);
			if (emptyDetail) {
                ElMessage.warning(`${emptyDetail.name}-${emptyDetail.label}库存不足，无法出库`);
            } else {
                ElMessage.warning('库存不足，无法出库');
            }
			return
		}
        const userinfo = Storage.getItem('userinfo');
		let params = {
			type: inventory_type.value,
			operator: userinfo.strator_nickname,
			operator_id: userinfo.id,
            batch_no: dataForm.batch_no,
            remark: dataForm.remark,
		}
        const contents = JSON.parse(JSON.stringify(options.value));
        contents.forEach(item => {
            item.attrList = [];
        })
        // 入库单数据
        if (inventory_type.value == 1) {
            params.in_time = dataForm.in_time;
            params.in_type = dataForm.in_type;
            params.supplier_name = dataForm.supplier_name;
            params.status = status;
            params.contents = JSON.stringify(contents);
        }
        // 出库单数据
        if (inventory_type.value == 2) {
            params.out_time = dataForm.out_time;
            params.out_type = dataForm.out_type;
            params.customer_name = dataForm.customer_name;
            params.department_id = dataForm.department_id;
            if(dataForm.department_id){
                params.department_name = departmentList.value.find(i => i.value == dataForm.department_id)?.label;
            }
            params.status = status;
            params.contents = JSON.stringify(contents);
        }
		if (dataForm.id) {
            params.id = dataForm.id;
            params.updated_at = timeResetDate();
        } else {
            delete params.id;
        }
        if(isFt.value){
            params.isFt = 1;
            params.share_contents = share_contents.value;
            params.purchase_no = purchase_no.value;
        }
        console.log(params);
        // return;
        if (status == 2) {
            ElMessageBox.confirm(`是否确定${inventory_type.value==1?'入库':'出库'}?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    btnloading.value = true;
                    addInventory(params)
                        .then((res: any) => {
                            if (res.status == 'success') {
                                ElMessage.success({
                                    message: params.id?'编辑成功':'添加成功',
                                    duration: 500,
                                    onClose: () => {
                                        visible.value = false
                                        emit('refreshDataList')
                                    }
                                })
                            } else {
                                btnloading.value = false
                                ElMessage.error({
                                    message: res.message || '提交失败',
                                    duration: 1200
                                })
                            }
                        })
                        .catch(() => {
                            btnloading.value = false
                        })
                })
        } else {
            btnloading.value = true;
            addInventory(params)
                .then((res: any) => {
                    btnloading.value = false;
                    if (res.status == 'success') {
                        ElMessage.success({
                            message: params.id?'编辑成功':'添加成功',
                            duration: 500,
                            onClose: () => {
                                if(!params.id){
                                    visible.value = false
                                }
                                emit('refreshDataList')
                            }
                        })
                    } else {
                        btnloading.value = false
                        ElMessage.error({
                            message: res.message || '提交失败',
                            duration: 1200
                        })
                    }
                })
                .catch(() => {
                    btnloading.value = false
                })
        }
	})
}
// type：1哑光，2荧光，3珠光，len颜色数量
const outInvent = (type, len) => {
    const num = prompt("输入出库数量(默认为空)","");
    let nowIndex = options.value.length;
    let idList = [];
    let lenList = [];
    if(type==1){
        idList = [3,8,4,6,7,10,5,11,9,12,14,13];
        if(len==12){
            lenList = [3,8,4,6,7,10,5,11,9,12,14,13];
        }else{
            lenList = [3,8,4,6,7,5,10,9,11,12,14,13];
        }
    }
    if(type==2){
        idList = [27,32,28,30,31,34,29,38,33,37,36,35];
        if(len==12){
            lenList = [27,32,28,30,31,34,29,38,33,37,36,35];
        }else{
            lenList = [27,32,28,30,31,29,34,33,38,37,36,35];
        }
    }
    if(type==3){
        idList = [15,20,16,18,19,22,17,23,21,26,24,25];
        if(len==12){
            lenList = [15,20,16,18,19,22,17,23,21,26,24,25];
        }else{
            lenList = [15,20,16,18,19,17,22,21,23,26,24,25];
        }
    }
    // console.log(num);
    if(num === null){
        return;
    }
    let timex = 0;
    let idx = 0;
    let timer = setInterval(()=>{
        timex++;
        if(timex > len){
            timex = 0;
            clearInterval(timer);
            setTimeout(()=>{
                if(!options.value[0].productName){
                    options.value.splice(0,1);
                }
            },400)
            return;
        }
        options.value.push(
            {
                productId: '',
                batchNo: '',
                batch_id: '',
                productName: '',
                inventory: 0,
                make_price: 0,
                quantity: num || '',
                attrList: [],
                batchList: [],
            }
        )
        setTimeout(()=>{
            // console.log('nowIndex',nowIndex);
            options.value[nowIndex].productName = '心型染发夹';
            selectChange(nowIndex, '心型染发夹');
        }, 150)
        setTimeout(()=>{
            options.value[nowIndex].productId = lenList[idx];
            selectChange2(nowIndex, lenList[idx]);
            idx++;
            nowIndex++;
        }, 300)
    }, 450)
}
defineExpose({
	init
})
</script>
<style lang="scss" scoped>
:deep(){
    .el-date-editor {
        .el-input__wrapper {
            width: 100%;
            box-sizing: border-box;
        }
    }
}
</style>